"""
常用工具
"""
import hashlib
import json
import os.path
import random

from prettytable import PrettyTable

from conf.settings import USER_DIR
from db.dbhandler import read


def pretty_print(title_list, data_list, auto_index=False):
    """美化打印"""
    tb = PrettyTable(title_list)
    tb.add_rows(data_list)
    if auto_index:
        tb.add_autoindex('编号')
    print(tb)


def loop_input(msg, err_msg, func, *args):
    """循环输入"""
    while True:
        data = input(msg).strip()
        if func(data, *args):
            return data
        print(err_msg)


def is_user_exist(username):
    """用户是否已存在"""
    return os.path.exists(os.path.join(USER_DIR, f'{username}.json'))


def encryption_password(password, pass_salt=None):
    """密码加密"""
    # 加密 不传入密码盐
    if not pass_salt:
        pass_salt = ''
        # 动态密码盐
        for i in range(6):
            random_int = str(random.randint(0, 9))
            random_upper = chr(random.randint(65, 90))
            random_lower = chr(random.randint(97, 122))
            pass_salt += random.choice([random_int, random_lower, random_upper])

    # 解密 传入密码盐
    m = hashlib.md5(password.encode('utf8'))
    m.update(pass_salt.encode('utf8'))
    return m.hexdigest(), pass_salt  # 返回加密密文 和 盐


def login_auth(current_user):
    """登录认证装饰器"""

    def login(func):
        def inner(*args, **kwargs):
            from core.src import login
            if current_user:  # 已登录
                return func(*args, **kwargs)
            else:  # 未登录
                if login():  # 登录成功
                    return func(*args, **kwargs)

        return inner

    return login


def admin_auth(current_user):
    """管理员认证装饰器"""

    def login(func):
        def inner(*args, **kwargs):
            if not current_user[0].is_admin:  # 是非管理员
                print('该功能仅管理员可用!!!')
                return
            return func(*args, **kwargs)  # 是管理员

        return inner

    return login


def get_all_user():
    """获取全部用户"""
    user_list = [user_file.split('.')[0] for user_file in os.listdir(USER_DIR)]
    all_user_list = []
    for username in user_list:
        all_user_list.append(read(username))
    return all_user_list
